<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>

        <div>
          <el-form
            ref="questionForm"
            :model="questionForm"
            :rules="questionRules"
            label-width="100px"
          >
            <el-form-item prop="subjectID" label="学科：">
              <el-select
                @change="getRelativeLists(questionForm.subjectID)"
                style="width: 400px"
                v-model="questionForm.subjectID"
                placeholder="请选择学科"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in subjectIDList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="catalogID" label="目录：">
              <el-select
                style="width: 400px"
                v-model="questionForm.catalogID"
                placeholder="请选择目录"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in catalogIDList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="enterpriseID" label="企业：">
              <el-select
                style="width: 400px"
                v-model="questionForm.enterpriseID"
                placeholder="请选择企业"
              >
                <el-option
                  :label="item.company"
                  :value="item.id"
                  v-for="item in enterpriseIDList"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="province" label="城市：">
              <el-select
                @change="getCitysList"
                class="multipleSelect"
                style="width: 195px"
                v-model="questionForm.province"
                placeholder="请选择"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in provinceList"
                  :key="index"
                ></el-option>
              </el-select>

              <el-select
                class="multipleSelect"
                style="width: 195px"
                v-model="questionForm.city"
                placeholder="请选择"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in cityList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="direction" label="方向：">
              <el-select
                style="width: 400px"
                v-model="questionForm.direction"
                placeholder="请选择方向"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in directionList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="questionType" label="题型：">
              <el-radio-group
                v-model="questionForm.questionType"
                @change="updatedOptionsType"
              >
                <el-radio
                  :label="item.value + ''"
                  v-for="item in questionTypeList"
                  :key="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>

            <el-form-item prop="difficulty" label="难度：">
              <el-radio-group v-model="questionForm.difficulty">
                <el-radio
                  :label="item.value + ''"
                  v-for="item in difficultyList"
                  :key="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>

            <el-form-item ref="textEditor1" label="题干：" prop="question">
              <!--
                    vue父子组件双向数据绑定
                    .sync
                   :editorData='questionForm.question'
                    @update:editorData='questionForm.question=$event'

                    获取组件失焦事件
                    @blur="handleBlur"

                 -->
              <!-- <TextAreaEditor
                :isEdit='this.isEdit'
                @blur="handleBlur1"
                :editorData.sync="questionForm.question"
              ></TextAreaEditor> -->

              <TextAreaEditor
                @blur="handleBlur1"
                :editorData.sync="questionForm.question"
              ></TextAreaEditor>
            </el-form-item>

            <el-form-item v-if="noneOptions" label="选项：">
              <!-- 单选组 -->
              <el-radio-group
                v-if="fourOptions"
                v-model="right"
                @change="changeRadioValue"
              >
                <div
                  class="optionsContent"
                  v-for="item in questionForm.options"
                  :key="item.id"
                  style="height: 60px"
                >
                  <el-radio
                    :label="item.isRight === 1 ? item.isRight : item.id"
                    class="optionsRadio"
                  >
                    {{ item.code }}：
                    <el-input v-model="item.title"></el-input>
                  </el-radio>
                  <UpLoadImg
                    class="imgComponent"
                    :imageUrl.sync="item.img"
                  ></UpLoadImg>
                </div>
              </el-radio-group>

              <!-- 多选组 -->
              <el-checkbox-group
                v-else
                v-model="rightList"
                @change="changeMultipleValue"
              >
                <div
                  class="optionsContent"
                  v-for="item in questionForm.options"
                  :key="item.id"
                  style="height: 60px"
                >
                  <el-checkbox class="optionsRadio" :label="item.id">
                    {{ item.code }}：
                    <el-input v-model="item.title"></el-input>
                  </el-checkbox>
                  <UpLoadImg
                    :imageUrl.sync="item.img"
                    class="imgComponent"
                  ></UpLoadImg>
                </div>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="">
              <el-button
                @click="addOptions"
                v-if="noneOptions"
                :disabled="fourOptions"
                type="danger"
                size="small"
                >+增加选项与答案</el-button
              >
            </el-form-item>

            <el-form-item label="解析视频：">
              <el-input
                style="width: 400px"
                v-model="questionForm.videoURL"
              ></el-input>
            </el-form-item>

            <el-form-item ref="textEditor2" label="答案解析：" prop="answer">
              <TextAreaEditor
                @blur="handleBlur2"
                :editorData.sync="questionForm.answer"
              ></TextAreaEditor>
            </el-form-item>

            <el-form-item label="题目备注：">
              <el-input
                style="width: 400px"
                type="textarea"
                :rows="3"
                v-model="questionForm.remarks"
              >
              </el-input>
            </el-form-item>

            <el-form-item label="试题标签：">
              <el-select
                multiple
                style="width: 400px"
                v-model="questionForm.tags"
                placeholder="请选择试题标签"
              >
                <el-option
                  v-for="(item, index) in tagsList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if='!isEdit'>
              <el-button type="primary" @click="onSubmit">确认提交</el-button>
            </el-form-item>
            <el-form-item v-else>
              <el-button type="success" @click="onModify">确认修改</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple as subjectsSimple } from '@/api/hmmm/subjects'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { list as companysSimple } from '@/api/hmmm/companys'
import {
  provinces as provincesSimpl,
  citys as citysSimple
} from '@/api/hmmm/citys'
import { simple as tagsSimple } from '@/api/hmmm/tags'

import {
  add as addQuestion,
  update as updateQuestion,
  detail as detailQuestion
} from '@/api/hmmm/questions'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'

import TextAreaEditor from './QuestionsNew/TextAreaEditor'
import UpLoadImg from './QuestionsNew/UpLoadImg'
// import { createLogger } from 'vuex'

export default {
  name: 'QuestionsNew',
  components: {
    TextAreaEditor,
    UpLoadImg
  },

  data () {
    //  select procince, validate city
    const validCity = (rules, value, callback) => {
      if (this.questionForm.province && !this.questionForm.city) {
        callback(new Error('请选择地区'))
      } else {
        callback()
      }
    }

    return {
      // validate rules
      // trigger: ['blur', 'change'] 不输入任何内容直接提交，检验失败，输入内容，仍显示校验失败，因为此时触发的是change事件
      questionRules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科名称',
            trigger: ['blur', 'change']
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请选择目录名称',
            trigger: ['blur', 'change']
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请选择企业名称',
            trigger: ['blur', 'change']
          }
        ],
        province: [
          { required: true, message: '请选择城市名称', trigger: 'blur' },
          { validator: validCity, trigger: 'change' }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向名称',
            trigger: ['blur', 'change']
          }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入解析', trigger: 'blur' }]
      },

      // 如果为新增
      // 初始化表单内容
      questionFormInit: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1', // 单，多，简答
        difficulty: '1',
        question: '',
        videoURL: '',
        answer: '',
        remarks: '',
        tags: [], // 标签多选，tags为数组
        options: [
          {
            id: 105,
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: 106,
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: 107,
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: 108,
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      },
      //  初始化选项组
      optionsInit: [
        {
          id: 105,
          questionsID: 26,
          code: 'A',
          title: '',
          img: '',
          isRight: 0
        },
        {
          id: 106,
          questionsID: 26,
          code: 'B',
          title: '',
          img: '',
          isRight: 0
        },
        {
          id: 107,
          questionsID: 26,
          code: 'C',
          title: '',
          img: '',
          isRight: 0
        },
        {
          id: 108,
          questionsID: 26,
          code: 'D',
          title: '',
          img: '',
          isRight: 0
        }
      ],

      questionForm: {},

      // 判断是否为编辑状态
      isEdit: false,

      // dropped list
      subjectIDList: [],
      catalogIDList: [],
      enterpriseIDList: [],
      provinceList: [],
      cityList: [],
      directionList: [],
      questionTypeList: [],
      difficultyList: [],
      tagsList: [],

      //   options type and number
      optionsNumber: 69,
      fourOptions: true, // 是否为4个选项
      noneOptions: true, // 是否显示选项

      //   被选中项
      right: 1, // 单选isRight为1时被选中
      rightList: [] // 多选被选中项
    }
  },

  //   filter: {
  //     optionsNumberByType () {
  //       //   遍历判断选项个数
  //       this.optionsNumber.toString = questionType.forEach(item => {
  //         if (this.questionForm.questionType === item.label) {
  //           return item.value
  //         }
  //       })
  //     }
  //   },

  watch: {
    //  解决点击左侧录入试题菜单项新增试题重置表单
    '$route.query.id': function () {
      if (!this.$route.query.id) {
        this.isEdit = false
        this.questionForm = this.questionFormInit
        this.$refs.questionForm.resetFields()

        this.getAllSimpleList()
        this.optionsType()
      }
    }
  },

  created () {
    if (!this.$route.query.id) {
      this.isEdit = false
    } else {
      this.isEdit = true
    }

    this.getAllSimpleList()

    if (!this.isEdit) {
      // 新增试题
      // 初始化表单内容
      this.questionForm = this.questionFormInit
      this.optionsType()
    } else {
      //   编辑试题
      this.getFormData()
    }
  },

  methods: {
    //   选择学科下拉菜单内容，才能获取相联目录和标签列表
    async getRelativeLists (id) {
      // get directorys list
      const directorysRes = await directorysSimple({ subjectID: id })
      this.catalogIDList = directorysRes.data
      //   get  tags list
      const tagsRes = await tagsSimple({ subjectID: id })
      //   console.log(tagsRes)
      this.tagsList = tagsRes.data
    },

    // 点击选项时改变单选组双向绑定的值和isRight的值
    changeMultipleValue (val) {
      this.changeOptionsValue(val, this.questionForm.options)
    },

    // 点击选项时改变多选组双向绑定的值和isRight的值
    changeRadioValue (val) {
      this.changeOptionsValue(val, this.questionForm.options)
    },

    // print form data
    async getFormData () {
      const resAll = await detailQuestion({ id: this.$route.query.id })
      //   const resAll = await detailQuestion({ id: 37 })

      const res = resAll.data
      this.questionForm = res

      //   后端获取到的tags为字符串，转换成ele需要的数组
      if (this.questionForm.tags) {
        this.questionForm.tags = this.questionForm.tags.split(',')
      }

      //  获取到res之后，先判断选项类型，根据选项类型确定选项

      // 解决选项不按顺序排序问题
      if (this.questionForm.options.length) {
        const options = []

        this.questionForm.options.map(item => (
          item.code
        )).sort().map(item => {
          this.questionForm.options.forEach(data => {
            if (data.code === item) { options.push(data) }
          })
        })
        this.questionForm.options = options
      }

      //   单选时
      if (this.questionForm.questionType === '1') {
        this.noneOptions = true
        this.fourOptions = true
      }
      //  多选时
      if (this.questionForm.questionType === '2') {
        //   显示多选
        this.noneOptions = true
        this.fourOptions = false

        this.questionForm.options.forEach((item) => {
          if (item.isRight === 1) {
            // 根据isRight把被选中的id赋值给多选框组双向绑定的rightList
            this.rightList.push(item.id)
          }
          // 所有选项的label为item.id
          item.isRight = item.id
        })

        //  新增选项时，初始值optionsNumber
        if (this.questionForm.options.length) {
          this.optionsNumber += this.questionForm.options.length - 4
        } else {
          this.optionsNumber = 65
        }
      }
      //   简答时
      if (this.questionForm.questionType === '3') {
        this.noneOptions = false
        // 解决编辑试题时，简答切换单多选时，options不显示
        this.questionForm.options = this.optionsInit
      }
    },

    //  自定义组件触发element-ui的blur事件
    handleBlur1 (e) {
      // 解决点击左侧录入试题菜单项富文本组件校验事件不清除
      if (!this.$route.id) {
        return
      }
      this.$refs.textEditor1.$emit('el.form.blur', e) // 重点！
    },
    handleBlur2 (e) {
      // 解决点击左侧录入试题菜单项富文本组件校验事件不清除
      if (!this.$route.id) {
        return
      }
      this.$refs.textEditor2.$emit('el.form.blur', e) // 重点！
    },

    //   add option
    addOptions () {
      const newNumber = this.optionsNumber++
      const newLetter = String.fromCharCode(newNumber)

      if (!this.isEdit) {
        //  新增试题时新增选项
        const lastOptionAdd = this.questionForm.options[
          this.questionForm.options.length - 1
        ]
        this.questionForm.options.push({
          // 时间戳生成id不报错
          id: +new Date(),
          questionsID: lastOptionAdd.questionsID,
          code: newLetter,
          title: '',
          img: '',
          isRight: 0
        })
      } else {
        // 修改试题时新增选项
        // 解决多选项不存在时无法新增选项的问题
        // console.log(this.questionForm.options)
        let lastOption = {}
        if (this.questionForm.options.length) {
          lastOption = this.questionForm.options[
            this.questionForm.options.length - 1
          ]
        } else {
          lastOption = this.optionsInit[this.optionsInit.length - 1]
        }

        //   在原有最后一个选项的基础上新增
        this.questionForm.options.push({
          id: +new Date(),
          questionsID: lastOption.questionsID,
          code: newLetter,
          title: '',
          img: '',
          isRight: lastOption.isRight + 1
        })
      }
    },

    // 点击单选多选时改变选型
    updatedOptionsType () {
      this.optionsType()
    },

    async getAllSimpleList () {
      // get subjects list
      const subjectsRes = await subjectsSimple()
      this.subjectIDList = subjectsRes.data

      //   get companys list
      const companysRes = await companysSimple()
      this.enterpriseIDList = companysRes.data.items

      //   get  provinces list
      const provincesRes = await provincesSimpl()
      this.provinceList = provincesRes

      this.directionList = direction

      //   get question type list
      this.questionTypeList = questionType

      //   get difficulty list
      this.difficultyList = difficulty
    },

    //  get citys list
    async getCitysList () {
      if (this.questionForm.province) {
        const citysRes = await citysSimple(this.questionForm.province)
        this.cityList = citysRes
      }
    },

    onSubmit () {
      // validate
      this.$refs.questionForm.validate(async (valid) => {
        if (!valid) {
          return
        }

        // 修改tags为字符串
        if (this.questionForm.tags.length) {
          console.log(this.questionForm.tags)
          this.questionForm.tags = this.questionForm.tags.join()
        } else {
          this.questionForm.tags = this.questionForm.tags = ''
        }

        // 修改options的isRight为布尔值
        if (this.questionForm.questionType !== '3') {
          this.questionForm.options.forEach((item) => {
            if (item.isRight === 1) {
              item.isRight = true
            } else {
              item.isRight = false
            }
          })
        }

        await addQuestion(this.questionForm)
        // console.log(res)
        this.$router.push('/questions/list')
        this.$message.success('新增成功')
      })
    },

    onModify () {
      // validate
      this.$refs.questionForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        // 先将tags转化成后端需要的字符串
        if (this.questionForm.tags) {
          this.questionForm.tags.join(',')
        }

        // 修改options的isRight为布尔值
        if (this.questionForm.questionType !== '3') {
          this.questionForm.options.forEach((item) => {
            if (item.isRight === 1) {
              item.isRight = true
            } else {
              item.isRight = false
            }
          })
        }

        if (this.questionForm.questionType === '3') {
          this.questionForm.options = this.optionsInit
        }

        const res = await updateQuestion(this.questionForm)

        if (res.data.success) {
          this.$router.back()
          this.$message.success('修改成功')
        } else {
          this.$message.success('修改失败')
        }
      })
    },

    // 声明形参便于方法复用

    // 单/多选框组绑定值变化时
    changeOptionsValue (val, array) {
      // val：重选时被选中框的label，多选时为数组
      // array：传入单/多选框数组

      // 后端需要的isRight为布尔值
      if (val instanceof Array) {
        // 多选
        this.rightList = val
        array.forEach((item) => {
          if (this.rightList.includes(item.id)) {
            item.isRight = 1
          } else {
            item.isRight = 0
          }
        })
      } else {
        // 单选框组双向绑定的数据重置
        this.right = null
        array.forEach((item) => {
          item.isRight = item.id
          if (item.isRight === val) {
            item.isRight = 1
          } else {
            item.isRight = 0
          }
        })
        this.right = 1
      }
    },

    //   update options
    //   复用两次
    optionsType () {
      if (this.questionForm.questionType === '1') {
        //   解决多选切换单选时，可能多选的问题
        this.right = null

        this.noneOptions = true
        this.fourOptions = true

        // 解决编辑试题时，简答切换单多选时，options不显示
        // if (this.isEdit) {
        //   this.questionForm.options = this.optionsInit
        // }
      }
      if (this.questionForm.questionType === '2') {
        this.noneOptions = true
        this.fourOptions = false

        // if (this.isEdit) {
        //   this.questionForm.options = this.optionsInit
        // }
      }
      if (this.questionForm.questionType === '3') {
        this.noneOptions = false
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.el-form {
  margin-left: 30px;

  //   ::v-deep .el-form-item__label {
  //     margin-right: 5px;
  //   }

  .multipleSelect {
    margin-right: 10px;
  }

  .optionsContent {
    position: relative;
    margin-bottom: 20px;

    .optionsRadio {
      display: inline-block;
      line-height: 60px;
      width: 240px;
      margin-right: 60px;
    }

    .imgComponent {
      position: absolute;
      display: inline-block;
    }
  }
}
</style>
